import 'dart:io';

import 'package:netease_music_api/netease_music_api.dart';

class NeteaseMusicConvertingUrlProxy {
  // The HTTP server.
  late HttpServer _server;

  Uri convertToUri(String id) {
    return Uri(host: _server.address.host, port: _server.port, query: id);
  }

  // Starts the server.
  Future<void> start() async {
    // Start an HTTP server on a port decided by the OS.
    _server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
    // Handle requests.
    _server.listen((request) async {
      final id = request.uri.query;
      final data = await NeteaseMusicApi().songUrl([id]);
      final url = Uri.parse(data.data!.first.url!);
      request.response.redirect(url.replace(scheme: 'https'));
    });
  }

  // Closes the server.
  Future<dynamic> stop() => _server.close();
}
